/*
 
 Copyright (c) 2008, Nash Tsai
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 
 * Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in
 the documentation and/or other materials provided with the distribution.
 * Neither the name of the author nor the names of its
 contributors may be used to endorse or promote products derived
 from this software without specific prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 
 */


#include "libstatechart/state.hxx"
#include "libstatechart/state_machine.hxx"
#include "libstatechart/transition.hxx"

#include <cassert>


using namespace statechart;
using namespace boost;

//State::State(StateMachine& contextMachine, 
//             const char* name, 
//             State::HistoryType historyType, 
//             time_t timeoutMS)
//:Context(name)
//,mTimeoutMS(timeoutMS)
//,mContextMachine(contextMachine)
//,mContextState(NULL)
//,mHistoryType(historyType)
//,mHistoryState(NULL)
//{
//}

//State::State(StateMachine& ownerMachine, const State& copy)
//:mName(copy.mName)
//,mTimeoutMS(copy.mTimeoutMS)
//,mContextMachine(ownerMachine)
//,mContextState(NULL)
//,mEnableHistory(false)
//,mHistoryState(NULL)
//{
//   ownerMachine.addState(this);
//}

//State::State(State& contextState,
//             const char* name, 
//             time_t timeoutMS)
//:Context(name)
//,mTimeoutMS(timeoutMS)
//,mContextMachine(contextState.mContextMachine)
//,mContextState(&contextState)
//,mHistoryType(ht_None)
//,mHistoryState(NULL)
//{
//}

#include <boost/weak_ptr.hpp>

//static 
StatePtr State::create(Context& parentContext, const char* name, bool isConcurrent) throw()
{
   StatePtr state(new State(name, isConcurrent));

   state->mContextMachine = dynamic_cast<StateMachine*>(&parentContext);
   if (!(state->mContextMachine))
   {
      state->mContextState = dynamic_cast<State*>(&parentContext);
      assert(state->mContextState);
      State* i = state->mContextState;
      do 
      {
         state->mContextMachine = i->mContextMachine;
         i = i->mContextState;
      } while(!(state->mContextMachine));
      state->mContextMachine->addState(state);
      state->mContextState->addState(*state);
   }
   else
   {
      state->mContextMachine->addState(state);
   }
   return state;
}

State::State(const char* name, bool isConcurrent)
:Context(name)
,mIsConcurrent(isConcurrent)
,mHistoryType(ht_None)
,mHistoryState(NULL)
,mTimeoutMS(0)
,mContextMachine(NULL)
,mContextState(NULL)
{
}


//virtual 
State::~State()
{
}

// public
void State::addState(State& subState)
{
   assert(std::find(mSubStates.begin(), mSubStates.end(), &subState) == mSubStates.end());
   mSubStates.push_back(&subState);
}

// private
void State::doOnEnter(const Event& event)
{
   OnEnter(*mContextMachine, *this, event);
   if (mSubStates.size())
   {
      mSubStates[0]->doOnEnter(event);
   }
}

// private
void State::getEnteringStateList(State::StateListType& enteringStates, State& exitingState)
{
   if (mContextState && mContextState != exitingState.mContextState )
   {
      enteringStates.push_back(mContextState);
      mContextState->getEnteringStateList(enteringStates, exitingState);
   }
}

// private
bool State::process(const Event& event)
{
   for (TransitionListType::const_iterator i = mTransitions.begin();
        i != mTransitions.end(); ++i)
   {
      Transition* transition = (*i).get();
      if (transition->isMatch(event))
      {
         // do exit action
         State* exitingState = mContextMachine->mCurrent;
         while (exitingState != this)
         {
            exitingState->OnExit(*mContextMachine, *exitingState, event);
            exitingState = exitingState->mContextState;
         }
         if (mContextState)
            OnExit(*mContextMachine, *this, event);
         
         // do transition action?
         transition->OnAction(*mContextMachine, *(mContextMachine->mCurrent), transition->mToState, event);
         
         // do enter action
         StateListType enteringStates;
         transition->mToState.getEnteringStateList(enteringStates, *this);
         std::reverse(enteringStates.begin(), enteringStates.end());
         for(StateListType::iterator j = enteringStates.begin(); j != enteringStates.end();
             ++j)
         {
            (*j)->OnEnter(*mContextMachine, **j, event);
         }
         transition->mToState.doOnEnter(event);
         mContextMachine->mCurrent = &(transition->mToState);
         return true;
      }
   }
   if (mContextState)
      return mContextState->process(event);
   else
      return false;
}

// public
void State::addTransition(const char* transitionName, State& toState, shared_ptr<IPredicate> pred)
{
   mTransitions.push_back(shared_ptr<Transition>(new Transition(transitionName, toState, pred)));
}

namespace statechart
{
   struct FindTransitionPred
   {
      FindTransitionPred(const char* transitionName)
      :mTransitionName(transitionName)
      {
      }
      
      bool operator()(shared_ptr<Transition>& i) const
      {
         return (::strcmp(i->getName(), mTransitionName) == 0);
      }
      
      const char* mTransitionName;
   };
}

// public
shared_ptr<Transition> State::getTransition(const char* transitionName)
{
   TransitionListType::iterator found = std::find_if(mTransitions.begin(),
                                                  mTransitions.end(),
                                                  FindTransitionPred(transitionName));
   if (found != mTransitions.end())
      return *found;
   else
      return shared_ptr<Transition>();
}

// public
void State::clearActions()
{
   OnEnter.Clear();
   OnExit.Clear();
}

// public
time_t State::getTimeout() const
{
   return mTimeoutMS;
}

// public
void State::setTimeout(time_t newTimeoutMS)
{
   mTimeoutMS = newTimeoutMS;
}

// public
bool State::operator==(const State& rhs) const
{
   return this == &rhs;
}

// public
bool State::operator!=(const State& rhs) const
{
   return this != &rhs;
}

// public                          
const State* State::getOutermostContext() const
{
   if (mContextState)
   {
      if (mContextState->mContextState)
         return mContextState->getOutermostContext();
      else
         return mContextState;
   }
   return NULL;
}

// public
const State* State::getContext() const
{
   return mContextState;
}

// public
void State::clearHistory()
{
   mHistoryState = NULL;
}

